package cn.szzsi.common.controller;

import cn.szzsi.common.bean.SystemConfig;
import cn.szzsi.common.kit.CommonUtil;
import cn.szzsi.common.kit.SystemConfigUtil;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.SiteConfig;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.redis.Redis;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 前台类 - 前台基类
 *
 */
public class BaseController<M extends Model<M>> extends Controller {

	public static final String STATUS = "status";
	public static final String WARN = "warn";
	public static final String SUCCESS = "success";
	public static final String ERROR = "error";
	public static final String MESSAGE = "message";
	public static final String CONTENT = "content";
	public static final String TEMPLATE_SUFFIX = ".html";
	public static final String ERROR_PAGE = "error.html";
	public static final String COMMON = "common";

	// 排序方式
	public enum OrderType{
		asc, desc
	}
	private String property;// 查找属性名称
	private String keyword;// 查找关键字

	private String orderBy;// 排序字段
	private String orderType;// 排序方式


	protected String id;
	protected String[] ids;
	protected String logInfo;// 日志记录信息
	protected String redirectionUrl = "redirectionUrl";// 操作提示后的跳转URL,为null则返回前一页

	protected List<String> errorMessageList;

	public BaseController() {
		// 把class的变量保存起来，不用每次去取
		this.setModelClass(getClazz());
	}

	/**
	 * 获取M的class
	 *
	 * @return M
	 */
	@SuppressWarnings("unchecked")
	public Class<M> getClazz() {
		Type t = getClass().getGenericSuperclass();
		Type[] params = ((ParameterizedType) t).getActualTypeArguments();
		return (Class<M>) params[0];
	}

	protected Class<M> modelClass;

	public Class<M> getModelClass() {
		return modelClass;
	}

	public void setModelClass(Class<M> modelClass) {
		this.modelClass = modelClass;
	}

	/**
	 * 通用分页查找
	 */
	public void findByPage() {
//		findByPage(null);
	}
	/**
	 * 通用分页查找
	 */
	public void findByPage(String shopId,String tablename) {
		String select = "select *";
		String sqlExceptSelect = "from "+ tablename + " where 1 = 1 ";

		if (StrKit.notBlank(getProperty()) && StrKit.notBlank(getKeyword())) {
			sqlExceptSelect += "and " + getProperty() + " like '%" + getKeyword() + "%'";
		}

		if(shopId != null){
			sqlExceptSelect += " and shopId = '"+shopId+"'";
		}

		sqlExceptSelect += " order by " + getOrderBy() +" "+ getOrderType();
		Page<M> pager = getModel(getModelClass()).paginate(getParaToInt("pageNumber", 1), getParaToInt("pageSize", 20), select, sqlExceptSelect);
		setAttr("pager", pager);
	}

	/**
	 * 获取所有列表
	 */
	public List<M> getAll(String shopId,String tablename) {
		String select = "select *";
		String sqlExceptSelect = "from "+ tablename + " where 1 = 1 ";

		if (StrKit.notBlank(getProperty()) && StrKit.notBlank(getKeyword())) {
			sqlExceptSelect += "and " + getProperty() + " like '%" + getKeyword() + "%'";
		}

		if(shopId != null){
			sqlExceptSelect += " and shopId = '"+shopId+"'";
		}

		sqlExceptSelect += " order by " + getOrderBy() +" "+ getOrderType();

		List<M> list = getModel(getModelClass()).find(select+sqlExceptSelect);
		return list;
	}



	/**
	 * 商户通用分页查找
	 */
	public void findBusinessByPage(String uid,String tablename) {
		String select = "select *";
		String sqlExceptSelect = "from " + tablename + " where 1 = 1 ";

		if (StrKit.notBlank(getProperty()) && StrKit.notBlank(getKeyword())) {
			sqlExceptSelect += "and " + getProperty() + " like '%" + getKeyword() + "%'";
		}

		sqlExceptSelect += " and uid='"+uid+"' order by " + getOrderBy() +" "+ getOrderType();
		System.out.println(sqlExceptSelect);
		Page<M> pager = getModel(getModelClass()).paginate(getParaToInt("pageNumber", 1), getParaToInt("pageSize", 10), select, sqlExceptSelect);
		setAttr("pager", pager);
	}

	/**
	 * 通用查找全部
	 */
	public void getAllData(String tablename) {
		renderJson(Db.find("select * from "+tablename+" order by id asc;"));
	}

	/**
	 * 通用根据id查找
	 */
	public void getById(String tablename) {
		renderJson(Db.findById(tablename, getParaToInt("id")));
	}

	/**
	 * 通用新增
	 *
	 */
	public void saved(Model<M> model){
		model.set("id", CommonUtil.getUUID());
		model.set("createDate", new Date());
		model.save();
	}

	/**
	 * 通用修改
	 *
	 */
	public void updated(Model<M> model){
		model.set("modifyDate", new Date());
		model.update();
	}

	/**
	 * 通用删除
	 *
	 * @throws Exception
	 */
	public void delete() throws Exception {
		renderText(getModel(getModelClass()).delete() + "");
	}

	// 获取系统配置信息
	public SystemConfig getSystemConfig() {
		return SystemConfigUtil.getSystemConfig();
	}

	// 获取商品价格货币格式
	public String getPriceCurrencyFormat() {
		return SystemConfigUtil.getPriceCurrencyFormat();
	}

	// 获取商品价格货币格式（包含货币单位）
	public String getPriceUnitCurrencyFormat() {
		return SystemConfigUtil.getPriceUnitCurrencyFormat();
	}

	// 获取订单货币格式
	public String getOrderCurrencyFormat() {
		return SystemConfigUtil.getOrderCurrencyFormat();
	}

	// 获取订单货币格式（包含货币单位）
	public String getOrderUnitCurrencyFormat() {
		return SystemConfigUtil.getOrderUnitCurrencyFormat();
	}

	public void renderSuccessMessage(String message, String url){
		setAttr(MESSAGE, message);
		setAttr(redirectionUrl, url);
		render(CommonUtil.TEMPLATE_PATH+"/platform/web/success.html");
	}

	public void renderWapSuccessMessage(String message, String url, String path){
		setAttr(MESSAGE, message);
		setAttr(redirectionUrl, url);
		render(CommonUtil.getRealTemplatePath(path,"success.html"));
	}


	/**
	 * 店铺会关联模版对象
	 * 1、根据店铺的id和模版名称获取最终模版页面
	 * 2、并设置模版路径和系统基础配置参数
	 * @param page
	 * @param shopId
	 */
	protected void getTemplatePath(String shopId, String page){
	    setAttr("shopId",shopId);
		String path= getViewPath(shopId);
		if(!CommonUtil.PLATFORM_BUSINESS.equals(shopId)){
			SiteConfig siteConfig= SiteConfig.dao.getByShopId(shopId);
			setAttr("siteConfig",siteConfig);
			render(CommonUtil.getRealTemplatePath(path,page.concat(TEMPLATE_SUFFIX)));
		}else{
			render(CommonUtil.getRealTemplatePath(path,ERROR_PAGE));
		}
	}

    /**
     * 根据店铺的主键获取该店铺的模版路径
     * @param shopId
     * @return
     */
	protected String getViewPath(String shopId){
        String path=CommonUtil.getPathByUidAndType(shopId,CommonUtil.isMobileDevice(getRequest()));//获取模板路径
        if(StrKit.isBlank(path)){
            path = COMMON;
        }
        setAttr("path",path);
        return path;
    }

    /**
     * 获取出错的模版页面
     * @param shopId
     */
	protected void getErrorViewPage(String shopId){
        String path = getViewPath(shopId);
        render(CommonUtil.getRealTemplatePath(path,ERROR_PAGE));
    }

	// 输出JSON成功消息，返回null
	public void ajaxJsonSuccessMessage(String message) {
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, SUCCESS);
		jsonMap.put(MESSAGE, message);
		renderJson(jsonMap);
	}

	// 输出JSON错误消息，返回null
	public void ajaxJsonErrorMessage(String message) {
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, ERROR);
		jsonMap.put(MESSAGE, message);
		renderJson(jsonMap);
	}

	// 输出JSON警告消息，返回null
	public void ajaxJsonWarnMessage(String message) {
		setAttr(STATUS, WARN);
		setAttr(MESSAGE, message);
		renderJson();
	}

	public void addActionError(String error){
		setAttr("errorMessages", error);
		render("/_view/common/error_page.html");
	}

	/**
	 * 根据表名、属性名称、属性值判断在数据库中是否唯一(若新修改的值与原来值相等则直接返回true).
	 *
	 * @param tableName
	 *            表名
	 * @param propertyName
	 *            属性名称
	 * @param value
	 *            属性值
	 * @return boolean
	 */
	public boolean isUnique(String tableName, String propertyName, String value) {
		if (StrKit.notBlank(tableName) && StrKit.notBlank(propertyName) && StrKit.notBlank(value)) {
			String sql = "select * from " + tableName + " where " + propertyName + " = ? ";
			return Db.findFirst(sql,value) == null;
		}else{
			return false;
		}
	}

	// 获取当前登录商户，若未登录则返回null
	public Member getLoginMember() {
		//String id = getSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME);
		String id="";
		String _auth=getCookie("_auth");
		if(StrKit.notBlank(_auth)){
			id=getMemberId(getCookie("_auth"));
		}
		if(StrKit.isBlank(id)){
			id = getSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME);//session获取用户id
			//System.out.println("获取用户登陆id--------"+id);
		}
		if (StrKit.isBlank(id)) {
			return null;
		}
		Member loginMember = Member.dao.findById(id);
		//System.out.println("loginMember----------"+loginMember);

		return loginMember;
	}


	//从Redis获取用户信息
	public String getMemberId(String _auth){
		String userInfo= Redis.use("zshop").get(_auth);
		String memberId=null;
		if(StrKit.notBlank(userInfo)){
			JSONObject ui=new JSONObject(userInfo);
			//System.out.println("ui-------"+ui);
			memberId=ui.getString("id");
		}
		return memberId;

	}
	//获取当前商户id
	public String getUid(){
		Member member=getLoginMember();
		String uid="";
		if("super".equals(member.getStr("b_shoprank"))){
			uid=member.getStr("id");
		}else{
			if(StrKit.notBlank(member.getStr("shopId"))&&!member.getStr("shopId").equalsIgnoreCase("0")){
				uid = member.getStr("shopId");
			} else{
				uid=member.getStr("b_shoprank");
			}
		}
		return uid;
	}


	public String getProperty() {
		property = getPara("property","");
		return property;
	}

	public String getKeyword() {
		keyword = getPara("keyword","");
		return keyword;
	}

	public String getOrderBy() {
		orderBy = getPara("orderBy","createDate");
		return orderBy;
	}

	public String getOrderType() {
		orderType = getPara("orderType", OrderType.desc.name());
		return orderType;
	}


	/**
	 * pc模板路径
	 * @param name
	 */
	protected void pcTemplatePath(String name){
		render("/template/pc1/html/"+name);
	}

	/**
	 * wap模板路径
	 * @param name
	 */
	protected void wapTemplatePath(String name){
		render("/template/default/html/"+name);
	}

}
